import type { FC, MutableRefObject, PropsWithChildren } from 'react'
import { createContext, memo, useRef } from 'react'
import { useSetState, useUpdate, useUpdateEffect } from 'ahooks'
import Head from './head'
import styles from './index.module.scss'

interface IndexProps {

}
interface ContextProps {
  onOpenChange?: (v: boolean) => void
  setHeight?: (v: number) => void
  heightRef?: MutableRefObject<number>
  isOpen?: boolean
  height?: number
}
export const Context = createContext<ContextProps>({})

const Index: FC<PropsWithChildren<IndexProps>> = ({ children }) => {
  const ref = useRef<HTMLDivElement>(null)
  const heightRef = useRef<number>(0)
  const [state, setState] = useSetState({
    isOpen: true,
    height: 0,
  })
  const setHeight = () => {
    if (ref.current) {
      ref.current.style.height = `${state.isOpen ? heightRef.current + 52 : 22}px`
    }
  }
  const context = {
    isOpen: state.isOpen,
    height: state.height,
    onOpenChange: (v: boolean) => {
      setState({
        isOpen: v,
      })
    },
    setHeight: (h: number) => {
      heightRef.current = h
      setHeight()
    },
    heightRef,
  }

  useUpdateEffect(() => {
    setHeight()
  }, [state.isOpen])
  return (<Context.Provider value={context}>
    <div className={styles.mainItem} ref={ref}>
      {children}
    </div>
  </Context.Provider>)
}
type CompoundedComponent = React.ForwardRefExoticComponent<
IndexProps > & {
  Head: typeof Head
}
const MainItem = Index as CompoundedComponent
MainItem.Head = Head
export default MainItem
